package com.example.visitedsys.Config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.example.visitedsys.utils.AESUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionFactoryConfig  {

    private DruidDataSource dataSource;

    private  static ConnectionFactoryConfig connectionFactoryConfig;

    AESUtil aesUtil;

    private Connection getConnection() throws SQLException {
        Properties properties = new Properties();
        // 这里需要自己进行加密
        String user = "root";
        String password = "123456";
        String url = "jdbc:mysql://127.0.0.1/visited_sys?useUnicode=true&characterEncoding=gbk&useSSL=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Hongkong";
        String driverClassName = "com.mysql.cj.jdbc.Driver";
        properties.put("driverClassName",driverClassName);
        properties.put("url",url);
        try {
            properties.put("username", AESUtil.aesDecrypt(user));
            properties.put("password", AESUtil.aesDecrypt(password));
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            try {
                init();
            } catch (Exception e2) {
            }
        }finally {
            if(dataSource.getConnection()!=null){
                dataSource.getConnection().close();
            }
        }
        return  dataSource.getConnection();
    }

    public static Connection getDatabaseConnection() throws SQLException {
        if(connectionFactoryConfig==null){
            connectionFactoryConfig = new ConnectionFactoryConfig();
        }
        return connectionFactoryConfig.getConnection();


    }

    public void init(){
        try {
            if (dataSource != null) {
                dataSource.close();
            }
        } catch (Exception e) {
        }
    }
}